package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.apache.poi.ss.formula.functions.T;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeBindController {

    @Autowired
    UserMapper userMapper;


    @RequestMapping("callbackCode.do")
    public String callback(String code, HttpServletRequest request, HttpServletResponse response){
        System.out.println("接收到了 临时授权码 " +code);

        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " +  tokenByCode);
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的gitee的用户信息 " + JSON.toJSONString(userInfoByToken));

        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");

        // 修改当前登录用户

        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        userFromRequest.setGiteeId(giteeId);
        userFromRequest.setNickName(nickName);
        userFromRequest.setAvatarUrl(avatarUrl);

        userMapper.updateUser(userFromRequest);

        // 修改一下cookie中的用户信息  (重新加密用户)
        TokenUtils.responseTokenByCookie(userFromRequest,response,30);

        return "redirect:list.do";
    }
}
